package com.shujia.java.day20.demo2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
* @Description: UDPClient 发送端
* @Author: 王火火
* @Date: 2019/8/23 8:53
 *
 *
 * 创建DatagramSocket
 * 创建IP地址和Port
 * 创建数据包（创建IP地址和Port）
 * 发送数据
 * 关闭
 *
 *
 * 因为我这是一台电脑 发送端和接收端不能同时监听同一个端口号
*/
public class UDPClient {
    public static void main(String[] args) throws Exception{
        //要发送的数据
        byte[] bytes="hello,UDP".getBytes();
        int port=9000;//端口号
        //创建DatagramSocket
        DatagramSocket datagramSocket = new DatagramSocket();
        //向接收端发送数据
        //提供了InetAddress 127.0.0.1代表本机地址
        InetAddress ip = InetAddress.getByName("127.0.0.1");

        //创建数据包 DatagramPacket​(byte[] buf, int length,
        // InetAddress address 接收端的IP,
        // int port，接收端的port)
        DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,ip,port);
        //发送数据send​(DatagramPacket p)
        datagramSocket.send(datagramPacket);
        System.out.println("发送端发送的数据为:"+new String(bytes,0,bytes.length));

        //接收接收端返回的数据
        DatagramSocket datagramSocket1 = new DatagramSocket(9001);
        byte[] b=new byte[1024];
        //通过数据包接收数据
        DatagramPacket datagramPacket1 = new DatagramPacket(b,0,b.length);
        //开始接收数据
        datagramSocket1.receive(datagramPacket1);
        //输出接收的数据
        System.out.println("接收端返回的为:"+new String(datagramPacket1.getData(),0,datagramPacket1.getData().length));
        //关闭
        datagramSocket.close();
        datagramSocket1.close();
    }
}
